<template>
  <div class="medical-appointment">
    <!-- 医院选择 -->
    <el-card class="hospital-select">
      <template #header>
        <div class="card-header">
          <span>选择医院</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索医院名称"
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8" v-for="hospital in hospitals" :key="hospital.id">
          <el-card 
            class="hospital-card" 
            :class="{ active: selectedHospital?.id === hospital.id }"
            @click="selectHospital(hospital)"
          >
            <h3>{{ hospital.name }}</h3>
            <p>{{ hospital.address }}</p>
            <div class="hospital-info">
              <span>等级: {{ hospital.level }}</span>
              <span>科室: {{ hospital.department_count }}个</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 科室和医生选择 -->
    <el-card v-if="selectedHospital" class="department-select">
      <template #header>
        <div class="card-header">
          <span>选择科室和医生</span>
        </div>
      </template>

      <el-row :gutter="20">
        <!-- 科室列表 -->
        <el-col :span="6">
          <el-menu
            :default-active="selectedDepartment?.id"
            class="department-menu"
            @select="handleDepartmentSelect"
          >
            <el-menu-item 
              v-for="dept in departments" 
              :key="dept.id"
              :index="dept.id"
            >
              {{ dept.name }}
            </el-menu-item>
          </el-menu>
        </el-col>

        <!-- 医生列表 -->
        <el-col :span="18">
          <el-table :data="doctors" style="width: 100%">
            <el-table-column prop="name" label="医生姓名" width="120" />
            <el-table-column prop="title" label="职称" width="120" />
            <el-table-column prop="specialty" label="专长" />
            <el-table-column prop="schedule" label="出诊时间" width="200" />
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  link
                  @click="handleAppointment(row)"
                >
                  预约
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="预约挂号"
      width="500px"
    >
      <el-form
        ref="appointmentForm"
        :model="appointmentForm"
        :rules="appointmentRules"
        label-width="100px"
      >
        <el-form-item label="就诊人" prop="patient_name">
          <el-input v-model="appointmentForm.patient_name" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="appointmentForm.id_card" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="appointmentForm.phone" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="appointment_time">
          <el-date-picker
            v-model="appointmentForm.appointment_time"
            type="datetime"
            placeholder="选择就诊时间"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
          />
        </el-form-item>
        <el-form-item label="最晚结算时间" prop="latest_settlement_time">
          <el-date-picker
            v-model="appointmentForm.latest_settlement_time"
            type="datetime"
            placeholder="选择最晚结算时间"
            :disabled-date="disabledSettlementDate"
          />
        </el-form-item>
        <el-form-item label="就诊费用">
          <span class="fee">¥{{ selectedDoctor?.fee || 0 }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appointmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppointment">
            确认预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { 
  getHospitals,
  getDepartments,
  getDoctors,
  createAppointment
} from '@/api/medical'

// 搜索关键词
const searchKeyword = ref('')

// 医院列表
const hospitals = ref([])
const selectedHospital = ref(null)

// 科室和医生列表
const departments = ref([])
const selectedDepartment = ref(null)
const doctors = ref([])
const selectedDoctor = ref(null)

// 预约表单
const appointmentDialogVisible = ref(false)
const appointmentForm = ref({
  patient_name: '',
  id_card: '',
  phone: '',
  appointment_time: '',
  latest_settlement_time: null,
})

// 表单验证规则
const appointmentRules = {
  patient_name: [
    { required: true, message: '请输入就诊人姓名', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  appointment_time: [
    { required: true, message: '请选择就诊时间', trigger: 'change' }
  ],
  latest_settlement_time: [
    { required: true, message: '请选择最晚结算时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && appointmentForm.value.appointment_time && new Date(value) <= new Date(appointmentForm.value.appointment_time)) {
          callback(new Error('最晚结算时间必须晚于就诊时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

// 加载医院列表
const loadHospitals = async () => {
  try {
    const res = await getHospitals({ keyword: searchKeyword.value })
    hospitals.value = res.data
  } catch (error) {
    ElMessage.error('加载医院列表失败')
  }
}

// 搜索医院
const handleSearch = () => {
  loadHospitals()
}

// 选择医院
const selectHospital = async (hospital) => {
  selectedHospital.value = hospital
  selectedDepartment.value = null
  selectedDoctor.value = null
  await loadDepartments(hospital.id)
}

// 加载科室列表
const loadDepartments = async (hospitalId) => {
  try {
    const res = await getDepartments(hospitalId)
    departments.value = res.data
  } catch (error) {
    ElMessage.error('加载科室列表失败')
  }
}

// 选择科室
const handleDepartmentSelect = async (departmentId) => {
  selectedDepartment.value = departments.value.find(d => d.id === departmentId)
  await loadDoctors(departmentId)
}

// 加载医生列表
const loadDoctors = async (departmentId) => {
  try {
    const res = await getDoctors(departmentId)
    doctors.value = res.data
  } catch (error) {
    ElMessage.error('加载医生列表失败')
  }
}

// 预约挂号
const handleAppointment = (doctor) => {
  selectedDoctor.value = doctor
  appointmentDialogVisible.value = true
}

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 禁用小时
const disabledHours = () => {
  const hours = []
  for (let i = 0; i < 24; i++) {
    if (i < 8 || i > 17) {
      hours.push(i)
    }
  }
  return hours
}

// 禁用结算日期 (必须在就诊时间之后)
const disabledSettlementDate = (time) => {
  const appointmentTime = appointmentForm.value.appointment_time;
  if (!appointmentTime) {
    return true; // If appointment time is not set, disable all dates
  }
  return time.getTime() <= new Date(appointmentTime).getTime();
}

// 提交预约
const submitAppointment = async () => {
  try {
    await appointmentForm.value.validate()
    const res = await createAppointment({
      hospital_id: selectedHospital.value.id,
      department_id: selectedDepartment.value.id,
      doctor_id: selectedDoctor.value.id,
      patient_name: appointmentForm.value.patient_name,
      id_card: appointmentForm.value.id_card,
      phone: appointmentForm.value.phone,
      appointment_time: appointmentForm.value.appointment_time,
      latest_settlement_time: appointmentForm.value.latest_settlement_time,
    })
    if (res.code === 200) {
      ElMessage.success('预约成功，请在订单页面完成结算！')
      appointmentDialogVisible.value = false
      // 清空表单
      Object.assign(appointmentForm.value, {
        patient_name: '',
        id_card: '',
        phone: '',
        appointment_time: '',
        latest_settlement_time: null,
      })
    } else {
      ElMessage.error('预约失败：' + res.message)
    }
  } catch (error) {
    ElMessage.error('预约失败，请检查表单填写')
  }
}

onMounted(() => {
  loadHospitals()
})
</script>

<style scoped>
.medical-appointment {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.hospital-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.hospital-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.hospital-card.active {
  border: 2px solid #409EFF;
}

.hospital-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #666;
}

.department-menu {
  height: 400px;
  border-right: 1px solid #eee;
}

.fee {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}
</style> 